package cn.jellybmedia.basic.service.impl;

import cn.jellybmedia.basic.constant.BaseConstants;
import cn.jellybmedia.basic.exception.BusinessException;
import cn.jellybmedia.basic.service.ILoginService;
import cn.jellybmedia.basic.utils.AjaxResult;
import cn.jellybmedia.basic.utils.HttpUtil;
import cn.jellybmedia.basic.utils.MD5Utils;
import cn.jellybmedia.basic.utils.StrUtils;
import cn.jellybmedia.basic.vo.LoginVo;
import cn.jellybmedia.basic.vo.PhoneLoginVo;
import cn.jellybmedia.basic.vo.WechatVo;
import cn.jellybmedia.user.domain.Logininfo;
import cn.jellybmedia.user.domain.User;
import cn.jellybmedia.user.domain.Wxuser;
import cn.jellybmedia.user.mapper.LogininfoMapper;
import cn.jellybmedia.user.mapper.UserMapper;
import cn.jellybmedia.user.mapper.WxuserMapper;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WxuserMapper wxuserMapper;

     @Autowired
    private UserMapper userMapper;


    /**======================================================================================
    * @Title: account
    * @Description: 前端后台登录方法
    * @Author: Mr.Zhang
    * @Version: 1.0
    * @Date:  2022/7/7 16:32
    * @Parameters: [loginVo]
    * @Return java.util.HashMap<java.lang.String,java.lang.Object>
    ======================================================================================*/
    @Override
    public HashMap<String, Object> account(LoginVo loginVo) {
        // 接收数据
        String username = loginVo.getUsername();
        String password = loginVo.getPassword();
        String type = loginVo.getType();

        // 进行参数非空校验
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password) ||StringUtils.isEmpty(type)){
            throw new BusinessException("参数为空,请重新输入");
        }

        // 根据账号Username查询login表
        Logininfo logininfo = logininfoMapper.loadByAccount(username,type);

        // 判断查询额参数是否为空,因为查询有可能为空
        if (logininfo == null){
            throw new BusinessException("账号或密码错误,请检查后重新输入");
        }

        // 生成UUid
        String token = UUID.randomUUID().toString();


        // 放入redis中并设置有效时间为30分钟
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);

        // 将用户的命案信息滞空
        logininfo.setPassword("");
        logininfo.setSalt("");

        // 将token和用户信息保存导map中
        HashMap<String, Object> map = new HashMap<>();
        map.put("token",token);
        map.put("logininfo",logininfo);
        // 返回map
        return map;

    }

    /**======================================================================================
     * @Title: loginPhone
     * @Description: 手机验证码登录
     * @Author: Mr.Zhang
     * @Version: 1.0
     * @Date:  2022/7/9 16:04
     * @Parameters: [registerVo]
     * @Return void
    ======================================================================================
     * @return*/
    @Override
    public HashMap<String, Object> loginPhone(PhoneLoginVo phoneLoginVo) {
        // 手机号
        String phone = phoneLoginVo.getPhone();
        // 验证码
        String smsCodeValue = phoneLoginVo.getSmsCodeValue();

        String type = phoneLoginVo.getType();

        // 判断参数是否为空
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(smsCodeValue) ){
            throw new BusinessException("你输入了无效字符,请检查后重新输入");
        }

        // 判断两次手机号是否一致
        // 先获取上一次的手机号,需要用时间戳解出来
        String phoneCodeKey = BaseConstants.RegisterCodeConstants.BUSINESS_REGISTER_PREFIX + phone;
        Object phoneCodeValue = redisTemplate.opsForValue().get(phoneCodeKey);
        if (phoneCodeValue == null) {
            throw new BusinessException("验证码已过期,请重新获取验证码");
        }

        // 判断验证码是否正确
        String phoneCode = phoneCodeValue.toString().split(":")[1];

        if (!phoneCode.equalsIgnoreCase(smsCodeValue)){
            throw new BusinessException("验证码不正确,请重新输入验证码");
        }

        // 根据手机号查询用户
        Logininfo logininfo = logininfoMapper.loadByPhone(phone,type);


        // 判断查询额参数是否为空,因为查询有可能为空
        if (logininfo == null){
            throw new BusinessException("账号或密码错误,请检查后重新输入");
        }

        // 生成UUid
        String token = UUID.randomUUID().toString();


        // 放入redis中并设置有效时间为30分钟
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);


        // 将用户的命案信息滞空
        logininfo.setPassword("");
        logininfo.setSalt("");


        // 将token和用户信息保存导map中
        HashMap<String, Object> map = new HashMap<>();
        map.put("token",token);
        map.put("logininfo",logininfo);
        // 返回map
        return map;

    }

    /**======================================================================================
    * @Title: loginWechat
    * @Description: 微信登录的方法,查询是否有绑定User表中的数据,因为我们自己的用户表就是User表,所以需要查询User表
    * @Author: Mr.Zhang
    * @Version: 1.0
    * @Date:  2022/7/10 17:06
    * @Parameters: [wechatVo]
    * @Return cn.jellybmedia.basic.utils.AjaxResult
    ======================================================================================*/
    @Override
    public AjaxResult loginWechat(WechatVo wechatVo) {
        // 判断接收的参数是否为空
        String code = wechatVo.getCode();
        if (StringUtils.isEmpty(code)){
            throw new BusinessException("参数非法,请检查后重新输入");
        }

        // 根据code获取access_token与openid
        String tokenUrl = BaseConstants.loginWechatConstants.TOKEN_URL
                .replace("APPID", BaseConstants.loginWechatConstants.APPID)
                .replace("SECRET", BaseConstants.loginWechatConstants.SECRET)
                .replace("CODE", code);

        // 发起请求获取到Json字符串
        String jsonstr = HttpUtil.httpGet(tokenUrl);

        // 根据Json字符串获取到需要access_token与openid
        JSONObject jsonObject = JSONObject.parseObject(jsonstr);

        // 根据openid查询t_weuser表
        Wxuser wxuser = wxuserMapper.loadByOpenId(jsonObject.getString("openid"));


        // 判断wxuser是否存在,根据用户的id和查询的结果
        if (wxuser != null && wxuser.getUserId() !=null){

            Logininfo logininfo = logininfoMapper.loadByUserId(wxuser.getUserId());

            // 生成UUid
            String token = UUID.randomUUID().toString();


            // 放入redis中并设置有效时间为30分钟
            redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);


            // 将用户的命案信息滞空
            logininfo.setPassword("");
            logininfo.setSalt("");


            // 将token和用户信息保存导map中
            HashMap<String, Object> map = new HashMap<>();
            map.put("token",token);
            map.put("logininfo",logininfo);
            // 返回map
            return AjaxResult.getAjaxResult().setResultObj(map);
        }
        // 如果走到这一步,那么用户是肯定没有进行绑定的,所以我们需要跳转到绑定页面,让他进行绑定
        // 同时我们需要传输接收到的两个数据access_token与openid.也一并传输过去
        //StringBuffer stringBuffer = new StringBuffer();
        //stringBuffer.append("?access_token=").append(access_token)
        //            .append("&openid=").append(openid);

        String paramStr = "?accessToken=" + jsonObject.getString("access_token") + "&openId=" + jsonObject.getString("openid");
        // 返回数据回去
        return AjaxResult.getAjaxResult().setSuccess(false).setResultObj(paramStr);
    }

    /**======================================================================================
    * @Title: wechatbinder
    * @Description: 微信绑定User用户
    * @Author: Mr.Zhang
    * @Version: 1.0
    * @Date:  2022/7/10 18:44
    * @Parameters: [wechatVo]
    * @Return java.util.HashMap<java.lang.String,java.lang.Object>
    ======================================================================================*/
    @Override
    public HashMap<String, Object> wechatbinder(WechatVo wechatVo) {
        // 获取到前端的发送的参数
        String phone = wechatVo.getPhone();
        String accessToken = wechatVo.getAccessToken();
        String openId = wechatVo.getOpenId();
        String verifyCode = wechatVo.getVerifyCode();
        System.out.println(wechatVo);
        // 进行非空校验
        if (StringUtils.isEmpty(phone) ||StringUtils.isEmpty(accessToken)
            ||StringUtils.isEmpty(openId) ||StringUtils.isEmpty(verifyCode)){
            throw new BusinessException("参数不合法,请检查后重新输入");
        }

        String phoneCodeKey = BaseConstants.RegisterCodeConstants.BUSINESS_BINDER_PREFIX + phone;
        Object phoneCodeValueRedis = redisTemplate.opsForValue().get(phoneCodeKey);

        // 判断验证码是否正确
        String phoneCode = phoneCodeValueRedis.toString().split(":")[1];
        if (!phoneCode.equalsIgnoreCase(verifyCode)){
            throw new BusinessException("手机验证码错误，请重新输入！");
        }

        // 根据手机号查询用户是否存在
        User user = userMapper.loadByPhone(phone);

        // 3.1.不存在：初始化user&logininfo并保存
        Logininfo logininfo = null;
        if (user == null){
            user = smsCodeDto2User(phone);
            logininfo = user2Logininfo(user);
            logininfoMapper.save(logininfo);
            user.setLogininfoId(logininfo.getId());
            userMapper.save(user);
        }else {// 3.2.存在：查询Logininfo
            logininfo = logininfoMapper.loadByUserId(user.getId());
        }

        // 根据前端传递的accessToken&openId查询微信用户基本信息
        String wxUserUrl = BaseConstants.loginWechatConstants.WXUSER_URL
                .replace("ACCESS_TOKEN", accessToken)
                .replace("OPENID", openId);
        String wxUserStr = HttpUtil.httpGet(wxUserUrl);

        // 5.通过JSONObject方法将JSON字符串转换为指定对象
        Wxuser wxuser = JSONObject.parseObject(wxUserStr, Wxuser.class);
        System.out.println(wxuser);
        // 5.保存wxUser对象，并且需要设置userId字段为user对象的主键
        wxuser.setUserId(user.getId());
        wxuserMapper.save(wxuser);


        // 6.返回成功登录map
        // 5.生成UUID作为key
        String token = UUID.randomUUID().toString();
        // 6.将uuid&&logininfo设置到redis中，设置30分钟有效期
        redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);
        // 7.把Logininfo对象的敏感信息置为空，作为value
        logininfo.setSalt("");
        logininfo.setPassword("");
        // 8.将uuid&&logininfo存入到map中，返回给前端
        HashMap<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("logininfo", logininfo);
        return map;
    }


    private User smsCodeDto2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        String saltPassword = MD5Utils.encrypByMd5(salt + "1");
        user.setPassword(saltPassword);
        user.setSalt(salt);
        // 此处最好给用户发个短信，告知他初始密码是多少
        return user;
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user, logininfo);
        logininfo.setType(1);
        return logininfo;
    }
}




